const models = require("../models/user");
const {responseWrite} = require("./common");
const {decrypt, encrypt} = require("../utils/bcryptUtil");

const logout = (req, res, next) => {
    req.session = null
    responseWrite(res, {message: "退出成功"})
}

const login = (req, res, next) => {
    let { username, password } = req.body
    if( !username || !password ){
        responseWrite(res, {message: "用户名或密码不能为空"}, 300)
        return
    }
    models.findUser(username).then(async userInfo => {
        if( !userInfo ){
            responseWrite(res, {message: "用户名不存在"}, 300)
        }else{
            if( await decrypt(password, userInfo.password) ){
                req.session.username = username
                responseWrite(res, {message: "登录成功"})
            }else{
                responseWrite(res, {message: "密码错误"}, 300)
            }
        }
    })
}

const remove = (req, res, next) => {
    models.deleteUserById(req.body.id).then(info => {
        if( info.deletedCount )
            responseWrite(res, {message: "删除成功"})
        else
            responseWrite(res, {message: "删除失败"}, 300)
    })
}

const list = (req, res, next) => {
    models.findUserList().then(userList => {
        responseWrite(res, {userList})
    })
}

const register = async (req, res, next) => {
    let reqBody = req.body
    // 判断用户名和密码是否符合规范
    if( !reqBody.username || !reqBody.password ){
        responseWrite(res, {message: "用户名或密码不能为空"}, 300);
    }else{
        // 查找是否重复用户名
        models.findUser(reqBody.username).then(async (hasUser) => {
            if( !hasUser ){
                // 保存到数据库
                models.saveUser({
                    username: reqBody.username,
                    password: await encrypt(reqBody.password)
                }).then(() => {
                    responseWrite(res, {message: "注册成功"});
                })
            }else{
                responseWrite(res, {message: "该账号已存在"}, 300);
            }
        })
    }
}

// 用于批量创建用户的
const creator = async (req, res, next) => {
    let username = req.query.username
    for (let i = 0; i < 10; i++) {
        await models.saveUser({
            username: username + i,
            password: await encrypt('qwe123')})
    }
    responseWrite(res, {message: "批量生成成功"});
}

module.exports = {
    login, logout, register, creator, remove, list
}